package net.linlan.plat.comm.security;

import net.linlan.commons.core.ObjectUtils;
import net.linlan.man.admin.dto.AdminUserDto;
import net.linlan.man.admin.service.AdminUserService;
import net.linlan.frame.FrameAdminUser;
import net.linlan.plat.comm.service.SysPasswordService;
import net.linlan.plat.comm.service.SysPermissionService;
import net.linlan.utils.MessageUtils;
import net.linlan.utils.enums.UserStatus;
import net.linlan.utils.exception.CommonException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author Linlan
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private AdminUserService adminUserService;
    
    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        AdminUserDto user = adminUserService.selectUserByUsername(username);
        if (ObjectUtils.isEmpty(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new CommonException(MessageUtils.message("user.not.exists"));
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new CommonException(MessageUtils.message("user.password.delete"));
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new CommonException(MessageUtils.message("user.blocked"));
        }

        passwordService.validate(user);

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(AdminUserDto user)
    {
        return new FrameAdminUser(user.getId(), user.getDeptId(), user.getUsername(), user.getPassword(), user.getLastAppId(), permissionService.getMenuPermission(user));
    }
}
